#include "Network/MessageManager.h"
#include "Utils/Utils.h"
#include "Log.h"
#include "Network/Client.h"
#include "Expand/PluginsManager.h"
#include "Network/PackageManager.h"
#include "Network/Packages/MessagePackage.h"
#include "GameSingleton.h"

namespace PocketSurvival
{

    MessageManager::MessageManager() {}
    MessageManager::~MessageManager() {}

    bool MessageManager::handleMessage(std::string &message, ClientPtr &client)
    {
        if(message.length() <= 0)
        {
            return false;
        }
        if(client != nullptr)
        {
            if(message.length() > 512)
            {
                Log::Warn(fmt::format("玩家 {} 发送了过长的消息，已经屏蔽处理，消息长度: {}", client->nickname, message.length()));
                return false;
            }
            Log::Info(fmt::format("[{}]:{}", client->nickname, message), Log::LogType::PLAYER);
        }

        if(message[0] == '/')
        {
            // 指令处理...
            CmdRunType runType = GameSingleton::pluginsManager->processCmdMessage(client, message);
            if(runType == CmdRunType::NotFound)
            {
                GameSingleton::packageManager->addSendPackageToQueue(std::make_shared<MessagePackage>("命令不存在", client));
            }
            else if(runType == CmdRunType::NoAuth)
            {
                GameSingleton::packageManager->addSendPackageToQueue(std::make_shared<MessagePackage>("没有权限", client));
            }
            else if(runType != CmdRunType::Success)
            {
                client->disconnect();
            }
            return false;
        }
        sensitiveFilter.filterContent(message);
        return true;
    }

    void MessageManager::load()
    {
        sensitiveFilter.loadFile("./content/SensitiveWords.txt");
    }

    void MessageManager::save() {}

} // namespace PocketSurvival
